<template>
  <div class="question-generation">
    <div class="page-header">
      <h1>智能题目生成</h1>
      <p>使用AI技术智能生成高质量题目</p>
    </div>

    <el-row :gutter="24">
      <!-- 生成表单 -->
      <el-col :span="8">
        <el-card class="generation-form">
          <template #header>
            <span>生成配置</span>
          </template>

          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
          >
            <el-form-item label="学科" prop="subject">
              <el-select v-model="form.subject" placeholder="请选择学科">
                <el-option label="数学" value="math" />
                <el-option label="语文" value="chinese" />
                <el-option label="英语" value="english" />
                <el-option label="物理" value="physics" />
                <el-option label="化学" value="chemistry" />
                <el-option label="生物" value="biology" />
                <el-option label="历史" value="history" />
                <el-option label="地理" value="geography" />
                <el-option label="政治" value="politics" />
              </el-select>
            </el-form-item>

            <el-form-item label="知识点" prop="topic">
              <el-input
                v-model="form.topic"
                placeholder="请输入知识点或主题"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="难度" prop="difficulty">
              <el-select v-model="form.difficulty" placeholder="请选择难度">
                <el-option label="简单" value="easy" />
                <el-option label="中等" value="medium" />
                <el-option label="困难" value="hard" />
              </el-select>
            </el-form-item>

            <el-form-item label="题目类型" prop="question_type">
              <el-select v-model="form.question_type" placeholder="请选择题目类型">
                <el-option label="单选题" value="single_choice" />
                <el-option label="多选题" value="multiple_choice" />
                <el-option label="判断题" value="true_false" />
                <el-option label="简答题" value="short_answer" />
                <el-option label="论述题" value="essay" />
                <el-option label="填空题" value="fill_blank" />
              </el-select>
            </el-form-item>

            <el-form-item label="生成数量" prop="count">
              <el-input-number
                v-model="form.count"
                :min="1"
                :max="10"
                :step="1"
                controls-position="right"
              />
            </el-form-item>

            <el-form-item label="额外要求">
              <el-input
                v-model="form.additional_context"
                type="textarea"
                :rows="3"
                placeholder="可选：添加具体要求或说明"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                :loading="generating"
                @click="generateQuestions"
                :disabled="!canGenerate"
              >
                <el-icon><Magic /></el-icon>
                {{ generating ? '生成中...' : '生成题目' }}
              </el-button>
              <el-button @click="resetForm">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 使用统计 -->
        <el-card class="usage-stats" style="margin-top: 20px;">
          <template #header>
            <span>今日使用情况</span>
          </template>
          <el-descriptions :column="2" size="small">
            <el-descriptions-item label="生成次数">
              {{ usageStats.total_usage || 0 }}
            </el-descriptions-item>
            <el-descriptions-item label="成功率">
              {{ usageStats.success_rate || 0 }}%
            </el-descriptions-item>
            <el-descriptions-item label="本月使用">
              {{ usageStats.monthly_usage || 0 }}
            </el-descriptions-item>
            <el-descriptions-item label="剩余配额">
              {{ remainingQuota }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>

      <!-- 生成结果 -->
      <el-col :span="16">
        <el-card class="results">
          <template #header>
            <div class="results-header">
              <span>生成结果</span>
              <div class="actions">
                <el-button
                  v-if="generatedQuestions.length > 0"
                  type="success"
                  size="small"
                  @click="saveAllQuestions"
                >
                  <el-icon><Download /></el-icon>
                  保存全部
                </el-button>
                <el-button
                  v-if="generatedQuestions.length > 0"
                  size="small"
                  @click="exportQuestions"
                >
                  <el-icon><Export /></el-icon>
                  导出
                </el-button>
              </div>
            </div>
          </template>

          <!-- 加载状态 -->
          <div v-if="generating" class="loading-state">
            <el-progress
              :percentage="generateProgress"
              :status="generateStatus"
            />
            <p style="text-align: center; margin-top: 20px;">
              {{ generateStatusText }}
            </p>
          </div>

          <!-- 空状态 -->
          <el-empty
            v-else-if="!generating && generatedQuestions.length === 0"
            description="暂无生成结果，请配置参数后生成题目"
          />

          <!-- 题目列表 -->
          <div v-else class="questions-list">
            <div
              v-for="(question, index) in generatedQuestions"
              :key="question.id"
              class="question-item"
            >
              <div class="question-header">
                <span class="question-index">{{ index + 1 }}.</span>
                <span class="question-title">{{ question.title }}</span>
                <div class="question-meta">
                  <el-tag size="small" :type="getDifficultyType(question.difficulty)">
                    {{ getDifficultyText(question.difficulty) }}
                  </el-tag>
                  <el-tag size="small" type="info">
                    {{ getQuestionTypeText(question.question_type) }}
                  </el-tag>
                  <span class="score">{{ question.score }}分</span>
                </div>
              </div>

              <div class="question-content">
                <div v-html="question.content" />
              </div>

              <!-- 选择题选项 -->
              <div
                v-if="question.options && question.options.length > 0"
                class="question-options"
              >
                <div
                  v-for="(option, optIndex) in question.options"
                  :key="optIndex"
                  class="option-item"
                >
                  {{ String.fromCharCode(65 + optIndex) }}. {{ option }}
                </div>
              </div>

              <!-- 答案和解析 -->
              <div class="question-answer" v-if="showAnswer">
                <el-collapse>
                  <el-collapse-item title="查看答案和解析">
                    <div class="correct-answer">
                      <strong>正确答案：</strong>{{ question.correct_answer }}
                    </div>
                    <div class="explanation">
                      <strong>解析：</strong>
                      <div v-html="question.explanation" />
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </div>

              <!-- 操作按钮 -->
              <div class="question-actions">
                <el-button
                  type="primary"
                  size="small"
                  @click="saveQuestion(question)"
                >
                  <el-icon><Check /></el-icon>
                  保存
                </el-button>
                <el-button
                  size="small"
                  @click="editQuestion(question)"
                >
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="removeQuestion(index)"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Magic, Refresh, Download, Export, Check, Edit, Delete } from '@element-plus/icons-vue'
import { aiApi, type QuestionGenerationRequest, type GeneratedQuestion } from '@/api/ai'

// 响应式数据
const generating = ref(false)
const generateProgress = ref(0)
const generateStatus = ref<'success' | 'exception' | ''>('')
const generateStatusText = ref('')
const showAnswer = ref(false)
const generatedQuestions = ref<GeneratedQuestion[]>([])
const usageStats = ref<any>({})

// 表单数据
const form = ref<QuestionGenerationRequest>({
  subject: '',
  topic: '',
  difficulty: 'medium',
  question_type: 'single_choice',
  count: 3,
  additional_context: ''
})

// 表单验证规则
const rules = {
  subject: [
    { required: true, message: '请选择学科', trigger: 'change' }
  ],
  topic: [
    { required: true, message: '请输入知识点', trigger: 'blur' }
  ],
  difficulty: [
    { required: true, message: '请选择难度', trigger: 'change' }
  ],
  question_type: [
    { required: true, message: '请选择题目类型', trigger: 'change' }
  ],
  count: [
    { required: true, message: '请输入生成数量', trigger: 'blur' }
  ]
}

// 计算属性
const canGenerate = computed(() => {
  return form.value.subject && form.value.topic
})

const remainingQuota = computed(() => {
  const dailyLimit = 100
  const used = usageStats.value.monthly_usage || 0
  return Math.max(0, dailyLimit - used)
})

// 方法
const generateQuestions = async () => {
  try {
    generating.value = true
    generateProgress.value = 0
    generateStatus.value = ''
    generateStatusText.value = '正在调用AI服务...'

    const response = await aiApi.generateQuestions(form.value)

    if (response.success) {
      generateProgress.value = 100
      generateStatus.value = 'success'
      generateStatusText.value = `成功生成 ${response.questions.length} 道题目`
      generatedQuestions.value = response.questions
      ElMessage.success('题目生成成功')
      await loadUsageStats()
    } else {
      throw new Error(response.error || '生成失败')
    }
  } catch (error: any) {
    generateProgress.value = 0
    generateStatus.value = 'exception'
    generateStatusText.value = '生成失败'
    ElMessage.error(error.message || '生成题目失败')
  } finally {
    generating.value = false
  }
}

const resetForm = () => {
  form.value = {
    subject: '',
    topic: '',
    difficulty: 'medium',
    question_type: 'single_choice',
    count: 3,
    additional_context: ''
  }
  generatedQuestions.value = []
  showAnswer.value = false
}

const saveQuestion = async (question: GeneratedQuestion) => {
  try {
    // 这里应该调用后端API保存题目到题库
    ElMessage.success('题目保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const saveAllQuestions = async () => {
  try {
    for (const question of generatedQuestions.value) {
      await saveQuestion(question)
    }
    ElMessage.success('全部题目保存成功')
  } catch (error) {
    ElMessage.error('批量保存失败')
  }
}

const editQuestion = (question: GeneratedQuestion) => {
  // 打开编辑对话框
  ElMessageBox.prompt('编辑题目内容', '编辑题目', {
    inputValue: question.content,
    inputType: 'textarea'
  }).then(({ value }) => {
    question.content = value
    ElMessage.success('编辑成功')
  })
}

const removeQuestion = (index: number) => {
  generatedQuestions.value.splice(index, 1)
  ElMessage.success('删除成功')
}

const exportQuestions = () => {
  // 导出题目为Word或PDF
  const content = generatedQuestions.value.map((q, i) =>
    `${i + 1}. ${q.title}\n${q.content}\n答案：${q.correct_answer}`
  ).join('\n\n')

  const blob = new Blob([content], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = 'AI生成的题目.txt'
  link.click()
  URL.revokeObjectURL(url)
}

const loadUsageStats = async () => {
  try {
    const stats = await aiApi.getUsageStats()
    usageStats.value = stats
  } catch (error) {
    console.error('加载使用统计失败:', error)
  }
}

const getDifficultyType = (difficulty: string) => {
  const types = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return types[difficulty] || 'info'
}

const getDifficultyText = (difficulty: string) => {
  const texts = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return texts[difficulty] || difficulty
}

const getQuestionTypeText = (type: string) => {
  const texts = {
    single_choice: '单选题',
    multiple_choice: '多选题',
    true_false: '判断题',
    short_answer: '简答题',
    essay: '论述题',
    fill_blank: '填空题'
  }
  return texts[type] || type
}

// 生命周期
onMounted(() => {
  loadUsageStats()
})
</script>

<style scoped>
.question-generation {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.page-header p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.generation-form {
  height: fit-content;
}

.usage-stats {
  margin-top: 20px;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.actions {
  display: flex;
  gap: 8px;
}

.loading-state {
  padding: 40px 20px;
}

.questions-list {
  max-height: 600px;
  overflow-y: auto;
}

.question-item {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  background-color: #f9fafb;
}

.question-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.question-index {
  font-weight: 600;
  color: #1f2937;
}

.question-title {
  flex: 1;
  font-weight: 500;
  color: #374151;
}

.question-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.score {
  font-size: 12px;
  color: #6b7280;
}

.question-content {
  margin-bottom: 12px;
  line-height: 1.6;
  color: #374151;
}

.question-options {
  margin-bottom: 12px;
}

.option-item {
  padding: 4px 0;
  color: #4b5563;
}

.question-answer {
  margin-bottom: 12px;
}

.correct-answer {
  margin-bottom: 8px;
  color: #059669;
}

.explanation {
  color: #6b7280;
  line-height: 1.6;
}

.question-actions {
  display: flex;
  gap: 8px;
}

@media (max-width: 768px) {
  .question-generation {
    padding: 16px;
  }

  .el-col {
    margin-bottom: 16px;
  }

  .question-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .question-meta {
    margin-top: 4px;
  }

  .actions {
    flex-direction: column;
    width: 100%;
  }

  .question-actions {
    flex-wrap: wrap;
  }
}
</style>